package com.example.whm.lib;

import java.io.ByteArrayOutputStream;

import org.holoeverywhere.widget.ListView;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;


public class Utility {

	  public static void setListViewHeightBasedOnChildren(ListView listView) {
          //获取ListView对应的Adapter
          ListAdapter listAdapter = listView.getAdapter();
          if (listAdapter == null) {
                 return;
          }
         
          int totalHeight = 0;
          for (int i = 0, len = listAdapter.getCount(); i < len; i++) {   //listAdapter.getCount()返回数据项的数目
                 View listItem = listAdapter.getView(i, null, listView);
                 listItem.measure(0, 0);  //计算子项View 的宽高
                 totalHeight += listItem.getMeasuredHeight();  //统计所有子项的总高度
          }
         
          ViewGroup.LayoutParams params = listView.getLayoutParams();
          params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
          //listView.getDividerHeight()获取子项间分隔符占用的高度
          //params.height最后得到整个ListView完整显示需要的高度
          listView.setLayoutParams(params);
   }
	  
	  
	  public static int calculateInSampleSize(
	            BitmapFactory.Options options, int reqWidth, int reqHeight) {
	    // 原始图片的宽高
	    final int height = options.outHeight;
	    final int width = options.outWidth;
	    int inSampleSize = 1;

	    if (height > reqHeight || width > reqWidth) {

	        final int halfHeight = height / 2;
	        final int halfWidth = width / 2;

	        // 在保证解析出的bitmap宽高分别大于目标尺寸宽高的前提下，取可能的inSampleSize的最大值
	        while ((halfHeight / inSampleSize) > reqHeight
	                && (halfWidth / inSampleSize) > reqWidth) {
	            inSampleSize *= 2;
	        }
	    }

	    return inSampleSize;
	}  
	  
	  
	  public static Bitmap decodeSampledBitmapFromResource(byte[] bytes,
		        int reqWidth, int reqHeight) {

		    // 首先设置 inJustDecodeBounds=true 来获取图片尺寸
		    final BitmapFactory.Options options = new BitmapFactory.Options();
		    options.inJustDecodeBounds = true;
		    BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);

		    // 计算 inSampleSize 的值
		    //options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
            options.outHeight=reqHeight;
            options.outWidth=reqWidth;
		    // 根据计算出的 inSampleSize 来解码图片生成Bitmap
		    options.inJustDecodeBounds = false;
		   
		    return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
		}
	  
	  public static byte[] bitmap2byte(Bitmap b){
		  byte[] bytesImage;
		  ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
		  b.compress(Bitmap.CompressFormat.PNG, 100, baoStream);
		  bytesImage = baoStream.toByteArray();
		  return bytesImage;
	  }
	  
	  
	  
	  
	  
	  
}
